﻿using UnityEngine;

public class MonoSingleton<T> : MonoBehaviour where T:MonoBehaviour
{
    bool isInit = false;
    static T inst;
    static object _lock = new object();
    public static T Inst
    {
        get
        {
            lock(_lock)
            {
                if(inst == null)
                {
                    inst = Transform.FindObjectOfType<T>();
                    if(inst == null)
                    {
                        var go = new GameObject();
                        go.name = typeof(T).Name;
                        inst = go.AddComponent<T>();
                        GameObject.DontDestroyOnLoad(go);
                    }
                }
                var mono = inst as MonoSingleton<T>;
                if(!mono.isInit)
                {
                    mono.isInit = true;
                    (inst as MonoSingleton<T>).OnInitialize();
                }
            }
            return inst;
        }
    }

    public virtual void OnInitialize()
    {
    }
}
